﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Fleck;
using PServiceBus.Core.Manager;
using PServiceBus.Core.Runtime;

namespace PServiceBus.FleckWebSocket {
    public class FleckWebSocketServer : PServiceBus.Core.Interface.IWebSocketServer {

        WebSocketServer server;
        
        #region IWebSocketServer Members

        public void Start(string host, int port, bool secured) {
            FleckLog.Level = LogLevel.Info;
            server = new WebSocketServer(String.Format("ws{0}://{1}:{2}", secured ? "s" : string.Empty, host, port));
            
            if (secured) {
                ShellHelper.NetShAddUrlAcl(port);
                server.Certificate = new System.Security.Cryptography.X509Certificates.X509Certificate2(Cerfx);
            }

            server.Start(socket =>
            {
                var connection = new FleckWebSocketConnection(socket);
                socket.OnOpen = () => { WebSocketConnectionManager.Register(connection); };
                socket.OnMessage = message => OnMessage(connection, message);
                socket.OnError = error => OnError(connection, error);
                socket.OnClose = () =>
                {
                    WebSocketConnectionManager.UnRegister(connection);
                    OnClose(connection);
                };
            });
        }

        public void Close() {
            if (server == null) return;
            ShellHelper.NetShRemoveUrlAcl(server.Port);
            server.Dispose();

        }

        public string Cerfx { get; set; }

        public Action<Core.Interface.IWebSocketConnection, string> OnMessage { get; set; }

        public Action<Core.Interface.IWebSocketConnection, Exception> OnError { get; set; }

        public Action<Core.Interface.IWebSocketConnection> OnOpen { get; set; }

        public Action<Core.Interface.IWebSocketConnection> OnClose { get; set; }

        #endregion
    }
}
